
from django.shortcuts import render_to_response
from django.conf.urls.defaults import *
from django.contrib.auth import authenticate, login, logout
from betting.main.models import LoginForm, BankModel, UserProfile, UserBetsModel, RegisterForm, CommentForm, ChangePass, ChangeEmail, DailyBet
from betting.board.models import BetModel, BetModelForm
from django.template import RequestContext
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
import locale
import datetime
import math

def index(request):
        locale.setlocale(locale.LC_ALL, 'en_US')
        
        if request.user.is_authenticated():
            if request.method == 'POST':
                
                allbets = BetModel.objects.all()
                
                user=request.user
                for bet in allbets:
                   
                    betaction = request.POST.get('bet'+str(bet.id))
                    
                    if betaction == 'sell':
                        
                        usersbet = UserBetsModel.objects.get(user=user,bet=bet)
                        revenue = bet.price
                        
                        user_bank = BankModel.objects.get(user=request.user)
                        user_bank.bankroll += revenue
                        user_bank.current_bets -=1
                        user_bank.save()
                        
                        usersbet.premature = True
                        usersbet.pre_buy = False
                        usersbet.pre_price = bet.price
                        bet_return = bet.price-usersbet.price
                        usersbet.bet_return = math.fabs(bet_return)
                        if bet_return < 0:
                            usersbet.return_sign = 0
                        else:
                            usersbet.return_sign = 1
                            
                        usersbet.save()
                    elif betaction == 'buy':
                        usersbet = UserBetsModel.objects.get(user=user,bet=bet)
                        revenue = 10000-bet.price
                        
                        user_bank = BankModel.objects.get(user=request.user)
                        user_bank.bankroll += revenue
                        user_bank.current_bets -=1
                        user_bank.save()
                        
                        usersbet.premature = True
                        usersbet.pre_buy = False
                        usersbet.pre_price = bet.price
                        bet_return = usersbet.price-bet.price
                        usersbet.bet_return = math.fabs(bet_return)
                        if bet_return < 0:
                            usersbet.return_sign = 0
                        else:
                            usersbet.return_sign = 1
                        
                        usersbet.save()
            
            bank = BankModel.objects.get(user=request.user)
            bankroll = locale.format("%d",bank.bankroll,grouping=True)
            profile= UserProfile.objects.get(user=request.user)
            allbets = UserBetsModel.objects.filter(user=request.user).order_by('expired')
            
            total = bank.total_bets
            current = bank.current_bets
            
            dailybets = DailyBet.objects.order_by('-id')
            daily = False
            if dailybets.count()>0:
                daily = dailybets[0]
            
            
            
            return render_to_response('home.html',{'user': request.user,'bank': bank,'profile': profile,'bankroll':bankroll,'bets':allbets, 'total': total,'current': current,'page':'home','daily':daily}, context_instance = 
RequestContext(request))
        else:
            def errorHandle(error):
                    form= LoginForm()
                    return render_to_response('index.html', {
                                                             'error': error,
                                                             'form': form,'page':'home'},context_instance=RequestContext(request))
            if request.method == 'POST':
                form = LoginForm(request.POST)
                if form.is_valid():
                    username = request.POST['username']
                    password = request.POST['password']
                    user = authenticate(username=username,password=password)
                    if user is not None:
                            if user.is_active:
                                    login(request,user)
                                    return HttpResponseRedirect(reverse('betting.main.views.index'))
                            else:
                                error = u'account disabled'
                                return errorHandle(error)
                    else:
                            error = u'Invalid Login. Please try again'
                            return errorHandle(error)
                else:
                    error = u'form is invalid'
                    return errorHandle(error)
            else:
                    form = LoginForm()
                    return render_to_response('index.html', {
                                                             'form':form,'page':'home'}, context_instance=RequestContext(request))
        
def signup(request):
    def errorHandle(error):
        return render_to_response('signup.html', {'page':'signup',
                                                  'error': error,
                                                  'form': form},context_instance=RequestContext(request))
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            
            try:
                user=User.objects.get(username=form.cleaned_data['username'])
                error = "Username already exists."
                return render_to_response('signup.html', {'page':'signup','form':form,'error':error}, context_instance=RequestContext(request))
            except User.DoesNotExist:    
                newuser = User.objects.create_user(form.cleaned_data['username'],form.cleaned_data['email'],form.cleaned_data['password'])
                
                
                newuser.save()
                
                #create empty profile for new user and save to database
                newprof = UserProfile(user=newuser)
                newprof.password='placeholder'
                newprof.zip=request.POST['zip']
                newprof.save()
                
                #Pull data from form and save to profile in database
                form =  RegisterForm(request.POST, instance=newprof)
                userform = form.save()
                
                #Get username and password
                username=userform.username
                password = userform.password
                
                #Create Bank Model for User
                userbank = BankModel(user=newuser)
                userbank.bankroll=200000
                userbank.current_bets = 0
                userbank.total_bets = 0
                userbank.save()
                
                send_mail('BettorPolitics Account Created', 'Thank you for registering for a BettorPolitics Account. Your username and password are as follows:'+'\n\nUsername: '+newuser.username+"\nPassword: "+password+'\n\nYour account has been created with $200,000 of funds. We hope you enjoy the experience of betting on political options.\n\nIf you have questions or concerns, please contact us using our feedback form.\n\nThanks,\nThe BettorPolitics Team', 'customerservice@bettorpolitics.com',
    [newuser.email], fail_silently=True)
                
                #Authenticate user and login
                user = authenticate(username=username, password=password)
                login(request,user)
                
                return HttpResponseRedirect(reverse('betting.main.views.index'))
        else:
            error = u'form is invalid'
            return errorHandle(error)
    else:
        form = RegisterForm()
        return render_to_response('signup.html', {'form':form,'page':'signup'}, context_instance=RequestContext(request))

def odds(request):
    if request.method == 'POST':
        activebets = BetModel.objects.filter(active=True)
        for bet in activebets:  
            bet_odds = request.POST.get('odds'+str(bet.id))
            betaction = request.POST.get('bet'+str(bet.id))
            
            if bet_odds != '':
                if bet_odds.isdigit():
                    bet.price = int(bet_odds)
                    bet.save()

            if betaction == 'win':
                bet.win = True
                bet.outcome_set=True
                bet.active = False
                bet.expired = datetime.datetime.now()
                bet.save()
                
                check_bets = UserBetsModel.objects.filter(bet=bet)
                for bet_made in check_bets:
                    bet_made.expired = datetime.datetime.now()
                    if not bet_made.premature:
                        user=bet_made.user
                        bank = BankModel.objects.get(user=user)
                        if bet_made.buy:
                            action = "Buy"
                            bank.bankroll = bank.bankroll + bet.amount
                            bet_made.bet_return = bet.amount - bet_made.price
                            email_return = '$'+str(bet.amount - bet_made.price)
                            bet_made.return_sign = 1
                        else:
                            action = "Sell"
                            bet_made.bet_return = (bet.amount - bet_made.price)
                            email_return = '-$'+str(bet.amount - bet_made.price)
                            bet_made.return_sign = 0
                        bank.current_bets -=1
                        bank.save()
                            
                    bet_made.save()   
                    if not bet_made.premature:
                        send_mail('A Bet Has Expired: '+bet.description, 'Dear '+user.username+':\n\nThe following bet has expired: \n\nDetails:\nDescription: '+bet.description+"\nPrice: "+str(bet_made.price)+'\nOrder: '+action+'\nExpiration: '+bet.expired.strftime("%B %d, %Y, %I:%M %p")+'\nOutcome: Occurred'+'\nYour Return: '+email_return+'\n\n Your positions and balance have been updated accordingly.\n\nThanks,\nThe BettorPolitics Team', 'customerservice@bettorpolitics.com',[user.email], fail_silently=True) 
            elif betaction == 'loss':
                bet.win = False
                bet.outcome_set=True
                bet.active = False
                bet.expired = datetime.datetime.now()
                bet.save()
                
                check_bets = UserBetsModel.objects.filter(bet=bet)
                for bet_made in check_bets:
                    
                    bet_made.expired = datetime.datetime.now()
                    if not bet_made.premature:
                        user=bet_made.user
                        bank = BankModel.objects.get(user=user)
                        if bet_made.buy:
                            action = "Buy"
                            bet_made.bet_return = bet_made.price
                            email_return = '-$'+str(bet_made.price)
                            bet_made.return_sign = 0
                        else:
                            action = "Sell"
                            bank.bankroll = bank.bankroll + bet.amount
                            bet_made.bet_return = bet_made.price
                            email_return = '$'+str(bet_made.price)
                            bet_made.return_sign = 1
                        bank.current_bets -=1
                        bank.save()
                    
                    bet_made.save()
                    
                    if not bet_made.premature:
                        send_mail('A Bet Has Expired: '+bet.description, 'Dear '+user.username+':\n\nThe following bet has expired: \n\nDetails:\nDescription: '+bet.description+"\nPrice: "+str(bet_made.price)+'\nOrder: '+action+'\nExpiration: '+bet.expired.strftime("%B %d, %Y, %I:%M %p")+'\nOutcome: Did not occur'+'\nYour Return: '+email_return+'\n\n Your positions and balance have been updated accordingly.\n\nThanks,\nThe BettorPolitics Team', 'customerservice@bettorpolitics.com',[user.email], fail_silently=True)
        return HttpResponseRedirect(reverse('betting.main.views.book'))
    else: 
        if request.user.is_authenticated() and request.user.is_staff:
                allbets = BetModel.objects.filter(active=True).order_by('expired')
                expired = BetModel.objects.filter(active=False)
                
                expired_new = expired.filter(outcome_set=False).order_by('expired')
                expired_old = expired.filter(outcome_set=True).order_by('expired')
                
                expired_num = expired_old.count()
                expirednew_num = expired_new.count()
                bet_num = allbets.count
                form = BetModelForm()
                return render_to_response('book.html',{'page':'book','bets': allbets,'exp_count':expired_num,'count':bet_num,'form':form,'thisuser':request.user,'expired_old': expired_old,'expired_new':expired_new,'expnew_count':expirednew_num},context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect(reverse('betting.main.views.index'))
def book(request):
    if request.method == 'POST':
        activebets = BetModel.objects.filter(active=False,outcome_set=False)
        for bet in activebets:  
            
            betaction = request.POST.get('bet'+str(bet.id))
            
            if betaction == 'win':
                bet.win = True
                bet.outcome_set=True
                bet.save()
               
                check_bets = UserBetsModel.objects.filter(bet=bet)
                for bet_made in check_bets:
                    if not bet_made.premature:
                        user=bet_made.user
                        bank = BankModel.objects.get(user=user)
                        if bet_made.buy:
                            bank.bankroll = bank.bankroll + bet.amount
                            bet_made.bet_return = bet.amount - bet_made.price
                            bet_made.return_sign = 1
                        else:
                            bet_made.bet_return = (bet.amount - bet_made.price)
                            bet_made.return_sign = 0
                        bank.save()    
                    bet_made.save()    
            elif betaction == 'loss':
                bet.win = False
                bet.outcome_set=True
                bet.save()
                
                check_bets = UserBetsModel.objects.filter(bet=bet)
                for bet_made in check_bets:
                    if not bet_made.premature:
                        user=bet_made.user
                        bank = BankModel.objects.get(user=user)
                        if bet_made.buy:
                            bet_made.bet_return = bet_made.price
                            bet_made.return_sign = 0
                        else:
                            bank.bankroll = bank.bankroll + bet.amount
                            bet_made.bet_return = bet_made.price
                            bet_made.return_sign = 1
                        bank.save()
                        bet_made.save()

        return HttpResponseRedirect(reverse('betting.main.views.book'))
    else: 
        if request.user.is_authenticated() and request.user.is_staff:
                allbets = BetModel.objects.filter(active=True).order_by('expired')
                expired = BetModel.objects.filter(active=False)
                
                expired_new = expired.filter(outcome_set=False).order_by('expired')
                expired_old = expired.filter(outcome_set=True).order_by('expired')
                
                expired_num = expired_old.count()
                expirednew_num = expired_new.count()
                bet_num = allbets.count
                form = BetModelForm()
                return render_to_response('book.html',{'page':'book','bets': allbets,'exp_count':expired_num,'count':bet_num,'form':form,'thisuser':request.user,'expired_old': expired_old,'expired_new':expired_new,'expnew_count':expirednew_num},context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect(reverse('betting.main.views.index'))

def add(request):
    if request.method == 'POST':
        form = BetModelForm(request.POST)
        if form.is_valid():
        
            title = request.POST['title']
            description = request.POST['description']
            price = request.POST['price']
            amount = request.POST['amount']
            date = request.POST['expire_date']
            time = request.POST['expire_time']
            
            daily = form.cleaned_data['daily']
            datetime = date+" "+time
            
            new_bet = BetModel(title=title,description=description,price=price,amount=amount,active=True,win=False,expired=datetime)
            new_bet.save()
            
            
            
            if daily:
                dailybet = DailyBet(bet=new_bet)
                dailybet.save()
            
            
            return HttpResponseRedirect(reverse('betting.main.views.book'))
        else:
            allbets = BetModel.objects.filter(active=True)
            bet_num = allbets.count
            
            return render_to_response('book.html',{'page':'book','bets': allbets,'count':bet_num,'form':form,'thisuser':request.user},context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('betting.main.views.book'))
    
def feedback(request):
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():   
            anon = form.cleaned_data['anon']
            comment = form.cleaned_data['comment']
            user = request.user
            
            if anon:
                send_mail('Feedback for BettorPolitics Beta, from anonymous', comment, user.email,['oabudayyeh@gmail.com','jeremy.haber@gmail.com'],fail_silently=True)
            else:
                send_mail('Feedback for BettorPolitics Beta, from '+user.username, comment, 'customerservice@bettorpolitics.com',['oabudayyeh@gmail.com','jeremy.haber@gmail.com',user.email],fail_silently=True)
            
            message = "Thank you for your feedback!"
            return render_to_response('feedback.html',{'page':'feedback','message':message},context_instance=RequestContext(request))
        else:
            error = "Please enter a comment"
            form = CommentForm()
            return render_to_response('feedback.html',{'page':'feedback','error':error,'form':form},context_instance=RequestContext(request))
    else:
        if request.user.is_authenticated():
            form = CommentForm()
            return render_to_response('feedback.html',{'page':'feedback','form':form},context_instance=RequestContext(request))
        else:
            return HttpResponseRedirect(reverse('betting.main.views.index'))
        
def change_email(request):
    if request.method == 'POST':
        email = request.POST['email']
        
        user = request.user
        user.email = email
        profile = user.get_profile()
        profile.email = email 
        
        user.save()
        profile.save()
        return HttpResponseRedirect(reverse('betting.main.views.account'))
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('betting.main.views.account'))
        else:
            return HttpResponseRedirect(reverse('betting.main.views.index'))
        
def change_pass(request):
    if request.method == 'POST':
        password = request.POST['password']
    
        user = request.user
        user.set_password(password)
        user.save()
        
        message = "Password successfully changed!"
        
        profile = request.user.get_profile()
        
        passform = ChangePass()
        emailform = ChangeEmail()
        return render_to_response('account.html',{'page':'account','profile':profile,'passform':passform,'emailform':emailform,'message':message},context_instance=RequestContext(request))
 
    else:
        if request.user.is_authenticated():
            return HttpResponseRedirect(reverse('betting.main.views.account'))
        else:
            return HttpResponseRedirect(reverse('betting.main.views.index'))
    return
    
def account(request):
    if request.user.is_authenticated():
        profile = request.user.get_profile()
        
        passform = ChangePass()
        emailform = ChangeEmail()
        return render_to_response('account.html',{'page':'account','profile':profile,'passform':passform,'emailform':emailform},context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('betting.main.views.index'))
    
def standings(request):
    if request.user.is_authenticated():
        top_users = BankModel.objects.order_by('-bankroll')
    
        user_standings = []
        for theuser in top_users:
            if not theuser.user.is_staff:
                user_standings.append(theuser)
        
        
        count = user_standings.count
        
        if count<20:
            display = user_standings[:count]
        else:
            display = user_standings[:20]
            
        return render_to_response('standings.html',{'page':'standings','top_users':display},context_instance=RequestContext(request))
    else:
        return HttpResponseRedirect(reverse('betting.main.views.index'))
    
def signout(request):
    logout(request)
    return HttpResponseRedirect(reverse('betting.main.views.index'))

def share(request, bet_id):
    bet_share = BetModel.objects.get(pk=bet_id)
    
    return render_to_response('share.html',{'bet':bet_share},context_instance=RequestContext(request))


def teaser(request):
    return render_to_response('teaser.html',context_instance=RequestContext(request)) 
def faq(request):
    return render_to_response('faq.html',context_instance=RequestContext(request)) 
def check_expire():
    active_bets = BetModel.objects.filter(active=True)
    now = datetime.datetime.now()
    
    for bet in active_bets:
        if bet.expired <= now:
            bet.active = False
            bet.save()
            
            send_mail('A Bet Has Expired and Requires Attention', 'Dear Administrator:\n \tThe following bet has expired: '+bet.description+". Please visit your expired bets inbox to set the outcome as soon as possible.\n\nThanks,\nThe BettorPolitics Team", 'customerservice@bettorpolitics.com',
    ['oabudayyeh@gmail.com','jeremy.haber@gmail.com'], fail_silently=True)
            check_bets = UserBetsModel.objects.filter(bet=bet)
            for bet_made in check_bets:
                if not bet_made.premature:
                    if bet_made.buy:
                        action = "Buy"
                    else:
                        action = "Sell"
                    user=bet_made.user
                    send_mail('A Bet Has Expired: '+bet.description, 'Dear '+user.username+':\n\nThe following bet has expired: \n\nDetails:\nDescription: '+bet.description+"\nPrice: "+str(bet_made.price)+'\nOrder: '+action+'\nExpiration: '+bet.expired.strftime("%B %d, %Y, %I:%M %p")+'\n\n Your positions and balance will be updated shortly as soon as the bet outcome is decided.\n\nThanks,\nThe BettorPolitics Team', 'customerservice@bettorpolitics.com',
        [user.email], fail_silently=True)
                    bank = BankModel.objects.get(user=user)
                    bank.current_bets -= 1
                    bank.save()
                    
    return